<template>
  <div class="action-wrap">
    <ContentWrap>
      <div class="search-box">
        <el-input v-model="input" clearable />
        <el-button type="primary" @click="searchTableLeft()">
            <el-icon style="vertical-align: middle">
                <Search />
            </el-icon>
            <span style="vertical-align: middle">查询</span>
        </el-button>
        <el-button type="primary" @click="resetInput()">
            <el-icon style="vertical-align: middle"><RefreshRight /></el-icon>
            <span style="vertical-align: middle">重置</span>
        </el-button>
      </div>
      <div class="mb-10px">
        <ElButton type="primary" @click="AddAction(ruleFormRef)">
            <el-icon style="vertical-align: middle; color: #fff">
                <Plus />
            </el-icon>
            <span style="vertical-align: middle">新增角色</span>
        </ElButton>
      </div>
      <div class="choose-box">
        <p>
          已选择 角色名称： <i> {{ count }} </i> <span @click="onEmpty"> 清空 </span>
        </p>
      </div>
      <div class="table-box">
        <el-table ref="multipleTableRef" :data="tableData" style="width: 100%" v-loading="loading">
          <el-table-column property="roleName" label="角色名称" show-overflow-tooltip />
          <el-table-column property="roleCode" label="角色编码" show-overflow-tooltip />
          <el-table-column property="createTime" label="创建时间" show-overflow-tooltip />
          <el-table-column property="操作" label="操作" width="120">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="showRight(scope.row)">
                用户
              </el-button>
              <el-dropdown trigger="click" style="vertical-align: middle">
                <el-button link type="primary">
                  <span style="font-size: 12px">更多</span>
                  <el-icon style="vertical-align: middle; color: #1890ff"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="perssionView('角色权限配置', scope.row)">
                      授权
                    </el-dropdown-item>
                    <el-dropdown-item @click="action(scope.row, 'edit')">编辑</el-dropdown-item>
                    <el-dropdown-item @click="delData(scope.row, false)">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          :current-page="objParams.pageNo"
          :page-size="objParams.pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :small="false"
          :disabled="false"
          :background="false"
          layout="total, sizes, prev, pager, next"
          :total="objParams.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          style="margin-top: 10px; display: flex; justify-content: center"
        />
      </div>
    </ContentWrap>
    <!-- 右侧 -->
    <ContentWrap v-show="rightRole">
      <el-icon class="RightClose" @click="rightRole = !rightRole"><Close /></el-icon>
      <div class="search-box">
        用户账号：
        <el-input v-model="roleParams.username" clearable />
        <el-button type="primary" @click="searchTableright()">
            <el-icon style="vertical-align: middle">
                <Search />
            </el-icon>
            <span style="vertical-align: middle">查询</span>
        </el-button>
        <el-button type="primary" @click="resetInputUser()">
            <el-icon style="vertical-align: middle"><RefreshRight /></el-icon>
            <span style="vertical-align: middle">重置</span>
        </el-button>
      </div>
      <div class="mb-10px">
        <ElButton :loading="delLoading" @click="showUser(true)">
          {{ t('RoleManage.User') }}
        </ElButton>
      </div>
      <div class="table-box">
        <el-table
          ref="multipleTableRef"
          :data="roletableData"
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column property="username" label="用户账号" show-overflow-tooltip />
          <el-table-column property="realname" label="用户名称" show-overflow-tooltip />
          <el-table-column property="statusText" label="状态" show-overflow-tooltip />
          <el-table-column property="操作" label="操作" width="120">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="delRoleUser(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          :current-page="roleParams.pageNo"
          :page-size="roleParams.pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :small="false"
          :disabled="false"
          :background="false"
          layout="total, sizes, prev, pager, next"
          :total="roleParams.total"
          @size-change="rolehandleSizeChange"
          @current-change="rolehandleCurrentChange"
          style="margin-top: 10px; display: flex; justify-content: center"
        />
      </div>
      <!--<Search
        :schema="allSchemas.searchSchema"
        @search="setSearchParams"
        @reset="setSearchParams"
      />


      <Table
        v-model:pageSize="tableObject.pageSize"
        v-model:currentPage="tableObject.currentPage"
        :columns="allSchemas.tableColumns"
        :data="tableObject.tableList"
        :loading="tableObject.loading"
        :pagination="{
          total: tableObject.total
        }"
        @register="register"
      >
        <template #action="{ row }">
          <div class="action-wrap">
            <span class="btn-span" @click="action(row, 'false')">
              {{ t('exampleDemo.del') }}
            </span>
          </div>
        </template>
      </Table>-->
    </ContentWrap>
    <!-- 左侧编辑弹框 -->
    <Dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      maxHeight="auto"
      @close="formReset(ruleFormRef)"
    >
      <!-- <Write ref="writeRef" :current-row="currentRow" /> -->
      <el-form
        :model="formInline.data"
        :rules="rules"
        ref="ruleFormRef"
        class="demo-ruleForm"
        label-width="120px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formInline.data.roleName" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="formInline.data.roleCode" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="formInline.data.description" />
        </el-form-item>
      </el-form>
      <template #footer>
        <ElButton
          type="primary"
          :loading="loading"
          @click="saveAdd(ruleFormRef)"
          v-if="dialogTitle == '新增'"
        >
          {{ t('exampleDemo.save') }}
        </ElButton>
        <ElButton
          type="primary"
          :loading="loading"
          @click="saveEdit(ruleFormRef)"
          v-else-if="dialogTitle == '编辑'"
        >
          {{ t('exampleDemo.save') }}
        </ElButton>
        <ElButton @click="formReset(ruleFormRef)">{{ t('dialogDemo.close') }}</ElButton>
      </template>
    </Dialog>
    <!-- 左侧授权抽屉 -->
    <RoleDrawer ref="drawerRef" />
    <!-- 右侧添加用户弹框 -->
    <UserDialog ref="dialogRef" @getUserRoleList="getUserRoleList" />
  </div>
</template>
<script setup lang="ts" name="roleManage">
import { ContentWrap } from '@/components/ContentWrap'
import { Dialog } from '@/components/Dialog'
import Write from './components/Write.vue'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElTable, FormInstance, FormRules, ElMessageBox, ElMessage } from 'element-plus'
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { RoleTableData } from '@/api/table/types'
import { reactive, ref, unref } from 'vue'
import RoleDrawer from '@/views/System/RoleManage/components/drawer.vue'
import UserDialog from '@/views/System/RoleManage/components/UserDialog.vue'
import { useEmitt } from '@/hooks/web/useEmitt'
import { ArrowDown, Close } from '@element-plus/icons-vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
// import { getRoleTableListApi, delTableListApi, getUserRoleListApi } from '@/api/table/role'
import {
  getRoleListApi,
  postRoleAddApi,
  postDeleteRoleBatchApi,
  getUserRoleListApi,
  postRoleEditApi,
  postDeleteUserRole
} from '@/api/roleManage/index'
// import { TableColumn } from '@/types/table'
// interface userRightProps {
//   column: string
//   order: string
//   field: string
//   pageNo: string | number
//   pageSize: string | number
//   roleId: string
// }
interface userRightProps {
  pageNo: string | number
  pageSize: string | number
  roleId: string
  username: string
}
// const { push } = useRouter()
const input = ref('') // 左侧输入搜索项
const dialogVisible = ref(false) // 左侧新增，编辑弹框
const dialogTitle = ref('') // 左侧新增，编辑弹框标题
// const dialogUserVisible = ref(false) // 右侧添加用户
const count = ref('-')
const loading = ref(false)
const tableData: any = ref([])
const objParams = reactive({
  pageNo: 1,
  pageSize: 10,
  roleName: '',
  total: 0
})
const currentRow = ref({})
const writeRef = ref<ComponentRef<typeof Write>>()

// 定义ref
const ruleFormRef = ref<FormInstance>()
// 表单字段定义
const formInline: any = reactive({
  data: {
    createBy: '',
    createTime: '',
    delFlag: '',
    description: '',
    id: '',
    roleCode: '',
    roleName: '',
    tenantId: 0,
    updateBy: '',
    updateTime: ''
  }
})
// 验证
const rules = reactive<FormRules>({
  roleName: [
      { required: true, message: '请填写角色名称', trigger: 'blur' },
      { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' },
  ],
  roleCode: [
      { required: true, message: '请填写角色编码', trigger: 'blur' },
      { min: 1, max: 64, message: '长度不超过 64 个字符', trigger: 'blur' },
      { pattern: /^[^\u4E00-\u9FA5]+$/, message: '角色编码不可输入汉字', trigger: 'blur' }
  ]
})
// 添加角色/^[^\u4E00-\u9FA5]+$/
const saveAdd = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data = formInline.data
      const res = await postRoleAddApi(data)
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
      if (res) {
        ElMessage({
            type: res.code == 200 ? 'success' : 'warning',
            message: res.message
        })
        dialogVisible.value = false
        // tableObject.currentPage = 1
        getRoleApi('')
        formEl.resetFields()
      }
    } else {
      console.log('error submit!')
      return false
    }
  })
}
// 编辑角色
const saveEdit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data = formInline.data
      const res = await postRoleEditApi(data)
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
      if (res) {
          ElMessage({
              type: res.code == 200 ? 'success' : 'warning',
              message: res.message
          })
        dialogVisible.value = false
        // tableObject.currentPage = 1
        getRoleApi('')
        formEl.resetFields()
      }
    } else {
      console.log('error submit!')
      return false
    }
  })
}
// 获取角色列表
const getRoleApi = async (params) => {
  params ? (objParams.roleName = params) : ''
  const res = await getRoleListApi(objParams).finally(() => {
    loading.value = false
  })
  if (res) {
    tableData.value = res.result?.records
    objParams.total = res.result?.total
  }
}
getRoleApi('')
const searchTableLeft = () => {
  // getUserRoleList(input)
  getRoleApi(input)
}
const searchTableright = () => {
  getUserRoleList()
}
// 分页
const handleSizeChange = (val: number) => {
  objParams.pageSize = val
  getRoleApi('')
}
const handleCurrentChange = (val: number) => {
  objParams.pageNo = val
  getRoleApi('')
}

const resetInput = () => {
  input.value = ''
  getRoleApi('')
}
const resetInputUser = () => {
  roleParams.username = ''
  getUserRoleList()
}
const onEmpty = () => {
  rightRole.value = false
  count.value = '-'
}

// 右侧请求接口参数
// const userRight = ref<userRightProps>({
//   column: 'createTime',
//   order: 'desc',
//   field: 'id,,username,realname,status_dictText,action',
//   pageNo: '1',
//   pageSize: '10',
//   roleId: ''
// })
// const { register, tableObject, methods } = useTable<RoleRightTableData>({
//   defaultParams: { roleParams: '1' },
//   getListApi: getUserRoleListApi,
//   delListApi: delTableListApi,
//   response: {
//     list: 'result',
//     total: 'total'
//   }
// })
// const { getList, setSearchParams } = methods

// 这里是右侧根据角色ID查询用户列表的data
const roletableData = ref([]) // table数据
// 这是获取列表的传参
const roleParams = reactive({
  pageNo: 1,
  pageSize: 10,
  username: '',
  roleId: '',
  total: 0
})
const roleloading = ref(false) // 表格lodding
// table点击用户操作-右侧显示
const rightRole = ref(false)

const showRight = (row) => {
  count.value = row.roleName
  rightRole.value = true
  roleParams.roleId = row.id
  // roleParams.username = row.roleName
  getUserRoleList()
}

// 根据角色Id查询用户信息
const getUserRoleList = async () => {
  roleloading.value = true
  const res = await getUserRoleListApi(roleParams).finally(() => {
    roleloading.value = false
  })
  if (res) {
    roletableData.value = res.result?.records
    roleParams.total = res.result?.total
  }
}

// 分页
const rolehandleSizeChange = (val: number) => {
  roleParams.pageSize = val
  getUserRoleList()
}
const rolehandleCurrentChange = (val: number) => {
  roleParams.pageNo = val
  getUserRoleList()
}
// 删除角色用户
const delRoleUser = async (row) => {
  // loading.value = true
  ElMessageBox.confirm('是否确认删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let params = {
        roleId: roleParams.roleId,
        userIds: row.id
      }
      const res = await postDeleteUserRole(params)
        .catch(() => {})
        .finally(() => {
          // loading.value = false
        })
      if (res) {
        ElMessage({
          type: 'success',
          message: res.message
        })
        getUserRoleList()
      }
    })
    .catch(() => {
      // loading.value = false
    })
}

// useEmitt({
//   name: 'getList',
//   callback: (type: string) => {
//     if (type === 'add') {
//       // tableObject.currentPage = 1
//     }
//     getList()
//   }
// })

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'username',
    label: t('RoleManage.username'),
    search: {
      show: true
    }
  },
  {
    field: 'realname',
    label: t('RoleManage.realname')
  },
  {
    field: 'status_dictText',
    width: '200px',
    label: t('RoleManage.status_dictText')
  },
  {
    field: 'action',
    label: t('tableDemo.action')
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)
// 右侧数据
// const  useCrudSchemas(RCrudSchemas)

const formReset = (formEl: FormInstance | undefined) => {
  dialogVisible.value = false
  if (formEl) return
  formEl.resetFields()
}
const AddAction = (formEl: FormInstance | undefined) => {
  dialogTitle.value = t('exampleDemo.add')
  // tableObject.currentRow = null
  dialogVisible.value = true
}

const delLoading = ref(false)

// 删除角色
const delData = async (row) => {
  console.log(row)
  // delLoading.value = true
  ElMessageBox.confirm('是否确认删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await postDeleteRoleBatchApi(row.id).finally(() => {
        // delLoading.value = false
      })
      if (res) {
        objParams.pageSize = 10
        objParams.pageNo = 1
        ElMessage({
          type: 'success',
          message: res.message
        })
        getRoleApi('')
      }
    })
    .catch(() => {
      // delLoading.value = false
    })
}

const action = (row: RoleTableData, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  formInline.data = row
  dialogVisible.value = true
}

const dialogRef = ref<InstanceType<typeof UserDialog> | null>(null)
const showUser = (visible) => {
  let data = {
    type: visible,
    roleId: roleParams.roleId,
    func: getUserRoleList()
  }
  dialogRef.value?.acceptParams(data)
}
// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof RoleDrawer> | null>(null)
const perssionView = (title: string, rowData = {}) => {
  const params = {
    title,
    rowData: { ...rowData }
  }
  drawerRef.value?.acceptTreeParams(params)
}
</script>
<style scoped lang="less">
@import './index.less';
</style>
